<template>
  <div class="mainContainer">
    <div class="chatContainer">
      <div class="head">
        <span>聊天室: </span>
        <span v-if="contactContactUserData.hw == null">{{
          contactContactUserData.name
        }}</span>
      </div>
      <div class="bottom">
        <div class="friendList">
          <el-scrollbar height="100%">
            <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText"
              style="margin-bottom: 10px"
            >
            </el-input>
            <el-tree
              class="filter-tree"
              :data="userList"
              :props="userListProps"
              accordion
              @node-click="choseOneToChat"
            >
            </el-tree>
          </el-scrollbar>
        </div>
        <div class="chatBody">
          <div class="chat">
            <el-scrollbar style="height:100%;width:100%">
              <ul class="chatScroll">
                <li
                  v-for="message in chatRecords"
                  :key="message.id"
                  class="messageBox"
                >
                  <span v-text="message.ctime"> </span>
                  <!-- <div :class="'main' + (message.direction == 2 ? ' self' : '')">
                  <img
                    class="avatar"
                    width="45"
                    height="45"
                    :src="
                      message.direction == 2
                        ? message.ownerName
                        : message.contactName
                    "
                  /> -->
                  <div :class="message.direction == 2 ? 'right' : 'left'">
                    <span
                      v-text="
                        message.direction == 2
                          ? personalData.username
                          : contactContactUserData.name
                      "
                    ></span>
                    <!-- 文本 -->
                    <!-- <div
                    class="text"
                    v-emotion="message.content"
                    v-if="message.ctype == 1"
                  ></div> -->
                    <span> : </span>
                    <span v-if="message.ctype == 1">
                      {{ message.content }}
                    </span>

                    <!-- 图片 -->
                    <div class="text" v-else-if="message.ctype == 2">
                      <img
                        :src="message.content"
                        class="image"
                        alt="聊天图片"
                      />
                    </div>

                    <!-- 其他 -->
                    <div
                      class="text"
                      v-else
                      v-text="
                        '[暂未支持的消息类型:' +
                        message.ctype +
                        ']\n\r' +
                        message.content
                      "
                    ></div>
                  </div>
                </li>
              </ul>
            </el-scrollbar>
          </div>
          <div class="send">
            <el-card class="chatcard">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="dialogContent"
                maxlength="100"
                show-word-limit
                rows="4"
              >
              </el-input>
              <div class="content-right">
                <el-button @click="sendMessage">发送消息</el-button>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    // 传递的参数是对象字典类型
    userList: Array,
  },
  data() {
    return {
      userList2: "",
      search: "",
      tableData: null,
      filterText: "",
      userListProps: {
        label: "name",
        children: "hw",
      },
      // 当前聊天对象信息
      contactContactUserData: "",
      // 个人信息
      personalData: "",
      // 聊天记录
      chatRecords: "",
      dialogContent: "",
      // 实时聊天socket
      webSocket: "",
    };
  },
  watch: {
    userList() {},
  },
  created() {},
  mounted() {
    this.getPersonalInfo();
    this.chatroomInit();
    // this.enterChatroom();
  },
  methods: {
    getPersonalInfo() {
      this.$axios
        .get("user/info")
        .then((response) => {
          this.personalData = response.data;
          console.log(this.user);
        })
        .catch(function (error) {
          console.log("发送请求失败：" + error);
        })
        .then(function () {
          console.log("测试成功");
        });
    },
    choseOneToChat(data) {
      this.contactContactUserData = data;
      console.log("*********************");
      console.log(this.contactContactUserData);
      console.log("*********************");
      if (data.hw == null) this.getChatRecords();
    },
    getChatRecords() {
      var _this = this;
      let formData = new FormData();
      formData.append("contactId", this.contactContactUserData.id);
      this.$axios
        .post("chat/chatrecord", formData)
        .then((response) => {
          let stateCode = response.headers["state"];
          if (stateCode == "200") {
            this.chatRecords = response.data;
          } else if (stateCode == null) {
            this.$message.success("请求数据异常！");
          } else {
            this.$message.error(this.$enum.getDescByValue("STATE", stateCode));
          }
        })
        .catch(function (error) {
          let stateCode = error.response.headers["state"];
          if (stateCode != "") {
            _this.$message.error(
              _this.$enum.getDescByValue("STATE", stateCode)
            );
          } else {
            _this.$message.error("后端异常");
          }
        })
        .then(function () {});
    },
    sendMessage() {
      const data = {
        type: "SINGLE_SENDING",
        fromUserId: this.personalData.userId,
        toUserId: this.contactContactUserData.id,
        content: this.dialogContent,
      };
      this.webSocket.send(JSON.stringify(data));
      this.chatRecords.push({
        id: "",
        ctime: this.getNowDate(),
        ctype: 1,
        direction: 2,
        content: this.dialogContent,
        ownerId: this.personalData.userId,
        ownerName: this.personalData.userName,
        contactId: this.contactContactUserData.id,
        contactName: this.contactContactUserData.name,
      });

      this.dialogContent = ""
      // var map = new Map();
      // map.set("type","SINGLE_SENDING");
      // map.set("fromUserId",this.personalData.userId);
      // map.set("toUserId",this.contactContactUserData.id);
      // map.set("content",this.dialogContent);
      // var map2json=Map2Json(map);
      // if (map2json.length < 8000){
      //     webSocket.send(map2json);
      // }else {
      //     console.log("文本太长了，少写一点吧😭");
      // }
    },
    chatroomInit() {
      if (window.WebSocket) {
        this.webSocket = new WebSocket("ws://localhost:8082/ws");
      } else {
        alert("抱歉，您的浏览器不支持WebSocket协议!");
      }

      //连通之后的回调事件
      this.webSocket.onopen = function () {
        console.log("已经连通了websocket，接下来开始吧。。。");
        //                setMessageInnerHTML("已经连通了websocket");
      };
      //连接发生错误的回调方法
      this.webSocket.onerror = function () {
        console.log("出错了");
      };

      //连接关闭的回调方法
      this.webSocket.onclose = function () {
        console.log("连接已关闭...");
      };

      //接收到消息的回调方法
      this.webSocket.onmessage = function (event) {
        console.log("接收信息回调");
        var data = JSON.parse(event.data).data;
        switch (data.type) {
          case "REGISTER":
            console.log("REGISTER");
            break;
          case "SINGLE_SENDING":
            var fromUserId = data.fromUserId;
            var toUserId = data.toUserId;
            var content = data.content;
            console.log("SINGLE_SENDING");
            this.updateChatBox(fromUserId, toUserId, content);
            break;
          default:
            console.log("类型错误");
            break;
        }
      };
    },
    enterChatroom() {
      let data = {
        type: "REGISTER",
        userId: this.personalData.userId,
      };
      this.webSocket.send(JSON.stringify(data));
    },
    updateChatBox(fromUserId, toUserId, content) {
      console.log(fromUserId + "" + toUserId + content);
      // this.chatRecords.append({

      // })
    },
    getNowDate() {
      var date = new Date();
      var sign2 = ":";
      var year = date.getFullYear(); // 年
      var month = date.getMonth() + 1; // 月
      var day = date.getDate(); // 日
      var hour = date.getHours(); // 时
      var minutes = date.getMinutes(); // 分
      var seconds = date.getSeconds(); //秒
      // var weekArr = [
      //   "星期一",
      //   "星期二",
      //   "星期三",
      //   "星期四",
      //   "星期五",
      //   "星期六",
      //   "星期天",
      // ];
      // 给一位数的数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        sign2 +
        minutes +
        sign2 +
        seconds
      );
    },
  },
};
</script>

<style lang="less" scoped>
.mainContainer {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
.chatContainer {
  height: 80%;
  width: 80%;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid hsl(0, 2%, 61%);
  box-sizing: border-box;
}
.head {
  height: 10%;
  width: 100%;
  border: 1px solid hsl(0, 2%, 61%);
  box-sizing: border-box;
}
.bottom {
  height: 90%;
  width: 100%;
  display: flex;
  border: 1px solid hsl(0, 2%, 61%);
  box-sizing: border-box;
}
.friendList {
  height: 90%;
  width: 25%;
  display: block;
  padding: 10px;
  border: 1px solid hsl(0, 2%, 61%);
  box-sizing: border-box;
}
.chatBody {
  height: 90%;
  width: 75%;
  display: flex;
  box-sizing: border-box;
  flex-wrap: wrap;
}
.chat {
  height: 70%;
  width: 100%;
  display: flex;
  padding: 5px;
  border: 1px solid hsl(0, 2%, 61%);
  box-sizing: border-box;
}
.send {
  height: 30%;
  width: 100%;
  display: flex;
  padding: 5px;
  border: 1px solid hsl(0, 2%, 61%);
  box-sizing: border-box;
}
.chatcard {
  width: 100%;
  box-sizing: border-box;
}

.left {
  height: 30px;
  width: 100%;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
}
.right {
  height: 30px;
  width: 100%;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row-reverse;
  box-sizing: border-box;
}
.chatScroll {
  height: 100%;
  width: 100%;
  padding: 10px 15px;
  /*overflow-y: scroll;*/
  background-color: #f5f5f5;
  display: block;
  box-sizing: border-box;
}
.messageBox {
  height: auto;
  width: 100%;
  display: block;
  box-sizing: border-box;
}
// .time {
//     height: auto;
//   width: 100%;
//   justify-content: center;
// }
.content-right {
  display: flex;
  // justify-items: right;
  flex-direction: row-reverse;
  box-sizing: border-box;
}
</style>